/*
 * @Description: 格式转换登记列表
 * @Author: Rfan
 * @Date: 2022-11-19 16:12:07
 * @LastEditTime: 2022-12-08 16:29:09
 */

import { useEffect, useMemo, useState } from 'react';
import { Button, Space, Table } from 'antd';
import classNames from 'classnames/bind';
import { formatDate } from '@/utils';
import { useFormatMessage } from '@/utils/intlHelpers';
import { useConversionContext } from '../contexts/ConversionContext';
import EditConversionDialog from './dialogs/EditConversionDialog';
import type { ColumnsType } from 'antd/es/table';
import type { IPageQuery } from '@/interfaces/global';
import type { IRegConversionItem } from '@/interfaces/registration';
import type { IRegConversionListParams } from '@/api/registration/conversion';
import styles from '../styles/pageList.module.scss';

const cx = classNames.bind(styles);

const PageList = (props: any) => {
  const { className } = props;
  const { list, selectItems, setSelectKey, getRegConversionList, deleteItem, typeFilter } =
    useConversionContext();
  const formatMessage = useFormatMessage();

  const [loading, setLoading] = useState(false);
  const [total, setTotal] = useState(0);
  const [listQuery, setListQuery] = useState<IPageQuery<IRegConversionListParams>>({
    pageNo: 1,
    pageSize: 10,
    param: {}
  });
  // 加入鉴定批次弹窗可视状态
  const [editVisible, setEditVisible] = useState(false);
  // 选中内容

  const [selectData, setSelectData] = useState<IRegConversionItem>(null);

  useEffect(() => {
    if (listQuery && listQuery.param) {
      setLoading(true);
      getRegConversionList(listQuery)
        .then((res: any) => {
          setTotal(res?.totalCount);
        })
        .finally(() => {
          setLoading(false);
        });
    }
  }, [listQuery]);

  /**
   * @description 切换页码触发
   * @param {number} page 页码
   * @param {number} pageSize 每页条目数
   */
  const pageChange = (page: number, pageSize: number) => {
    setListQuery((state) => ({
      ...state,
      pageNo: page,
      pageSize
    }));
  };

  /**
   * @description : 表格选项相关设置
   * @param {number} selectedRowKeys 选择的项目的KEY
   */
  const onSelectChange = (selectedRowKeys: number[]) => {
    setSelectKey(selectedRowKeys);
  };

  /**
   * @description:  表格多选配置
   */
  const rowSelection = {
    selectItems,
    onChange: onSelectChange
  };

  const editItem = (item: any) => {
    setSelectData(item);
    setEditVisible(true);
  };

  const columns: ColumnsType<IRegConversionItem> = [
    { title: '序号', dataIndex: 'id', key: 'id' },
    {
      title: '登记时间',
      dataIndex: 'registrationTime',
      key: 'registrationTime',
      width: 120,
      render: (time: number) => formatDate(time)
    },
    { title: '单位名称', dataIndex: 'unitName', key: 'unit' },
    { title: '管理授权', dataIndex: 'managementAuth', key: 'managementAuth' },
    { title: '责任部门', dataIndex: 'responsibleDept', key: 'responsibleDept' },
    {
      title: '管理类型',
      dataIndex: 'type',
      key: 'type',
      render: (text: number) => typeFilter(text)
    },
    { title: '源格式', dataIndex: 'sourceFormat', key: 'sourceFormat' },
    { title: '目标格式', dataIndex: 'targetFormat', key: 'targetFormat' },
    { title: '文件装换数量', dataIndex: 'fileCount', key: 'fileCount' },
    { title: '系统描述', key: 'sysDesc' },
    { title: '完成情况', dataIndex: 'completeDesc', key: 'completeDesc' },
    {
      title: '操作时间',
      dataIndex: 'startTime',
      key: 'startTime',
      width: 170,
      render: (time, record) => `${formatDate(time)} - ${formatDate(record.endTime)}`
    },
    { title: '操作人', dataIndex: 'operator', key: 'operator' },
    { title: '填表人', dataIndex: 'registrant', key: 'registrant' },
    { title: '审核人', key: 'audit' },
    {
      title: formatMessage('tableAction'),
      key: 'action',
      className: cx('action-col'),
      render: (_text, record: any) => (
        <Space>
          <Button
            type="link"
            size="small"
            onClick={() => {
              editItem(record);
            }}
          >
            编辑
          </Button>
          <Button
            type="link"
            size="small"
            onClick={() => {
              deleteItem(record.id);
            }}
          >
            删除
          </Button>
        </Space>
      )
    }
  ];

  return (
    <div className={className}>
      <Table
        columns={columns}
        dataSource={list}
        loading={loading}
        rowKey="id"
        scroll={{ x: 'max-content' }}
        bordered
        rowSelection={rowSelection}
        pagination={{
          current: listQuery.pageNo,
          pageSize: listQuery.pageSize,
          total,
          onChange: pageChange
        }}
      />

      {useMemo(
        () =>
          selectData && (
            <EditConversionDialog
              visible={editVisible}
              data={selectData}
              onClose={() => {
                setEditVisible(false);
              }}
            />
          ),
        [editVisible]
      )}
    </div>
  );
};

export default PageList;
